package com.example.day09question.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.day09question.R;
import com.example.day09question.bean.Mess;
import com.example.day09question.net.MyService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * A simple {@link Fragment} subclass.
 */
public class TowFragment extends Fragment implements View.OnClickListener {


    private static final String TAG = "aaa";
    private View view;
    private ProgressBar mPb;
    private TextView mTvi;
    /**
     * 点击下载
     */
    private Button mButton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_tow, container, false);
        initView(inflate);

        EventBus.getDefault().register(this);
        ChPermission();
        return inflate;
    }

        private void ChPermission() {
            int i = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if(i!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
            }
        }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Reception(Mess mess){
        int type = mess.getType();
        if(type==1){
            mPb.setMax(mess.getMax());
        }if(type==2){
            mPb.setProgress(mess.getPer());
            mTvi.setText(mess.getBai()+"%");
        }
    }
    private void initView(View inflate) {
        mPb = (ProgressBar) inflate.findViewById(R.id.pb);
        mTvi = (TextView) inflate.findViewById(R.id.tvi);
        mButton = (Button) inflate.findViewById(R.id.button);
        mButton.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.button:
                getActivity().startService(new Intent(getActivity(),MyService.class));
                Log.e(TAG, "onClick: "+"啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊" );
                break;
        }
    }
}
